#coding=utf-8
import sys
import re
import datetime
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from bs4 import BeautifulSoup


def get_mac_address():
    import uuid
    node = uuid.getnode()
    mac = uuid.UUID(int = node).hex[-12:]
    return mac


def validate_mac_address():
    import urllib.request
    f = urllib.request.urlopen('http://amazon-ceping.xunhuanle.com/publicwelcome/getallmacaddress')
    ret_content_bytes = f.read()
    ret_content_str = ret_content_bytes.decode()
    return ret_content_str


mac_address = get_mac_address()
print("Your macaddress is below:")
print(mac_address)
validation_content = validate_mac_address()
if mac_address not in validation_content:
    print("Please submit your unicode '"+mac_address+"' to administrator!!!")
    sys.exit()

file_name = "found_url_"+datetime.datetime.now().strftime('%Y-%m-%d_%H_%M_%S')+".xls"
baseUrl = "https://www.google.com/search?num=100&q="

keyWords = input("keywords:")
print("Your input is:", keyWords)
pingFenInput = input("ping fen(x.x):")
print("Your ping fen input is:", pingFenInput)
pingLunInput = input("ping lun(x):")
print("Your ping lun input is:", pingLunInput)

driver = webdriver.Firefox()
driver.get(baseUrl+keyWords)

while 1:
    WebDriverWait(driver, 240).until(EC.presence_of_element_located((By.ID, 'pnnext')))
    soup = BeautifulSoup(driver.page_source, "html.parser")
    allItems = soup.select('div.g')
    for item in allItems:
        file = open(file_name, 'a')
        title = item.select('h3.r > a')
        if title is not None and len(title) > 0:
            title_href = title[0].get('href')
        else:
            title_href = ''

        pingFenEle = item.select('div.slp')
        if pingFenEle is not None and len(pingFenEle) > 0:
            pingFen = pingFenEle[0].text
            print(pingFen)
            pingFenArr = re.findall(r"\d+\.?\d*", pingFen)
            fen = float(pingFenArr[0])
            num = int(pingFenArr[1])

            if fen >= float(pingFenInput) and num >= int(pingLunInput):
                file.writelines(title_href)
                file.writelines('\n')
        file.close()

    driver.find_element_by_xpath("//a[@id='pnnext']").click()

driver.quit()




